package com.bosssoft.trainee.filter;

import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.interfaces.Claim;
import com.bosssoft.trainee.until.JwtUntil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.netty.ByteBufFlux;

import java.util.HashMap;
import java.util.Map;

/**
 * @author liuqiang
 * @date 2022/7/4 22:05
 * 全局Filter
 */
@Slf4j
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求
        ServerHttpRequest request = exchange.getRequest();
        //获取响应
        ServerHttpResponse response = exchange.getResponse();
        //获取token令牌
        String token = request.getHeaders().getFirst("token");
        if (request.getURI().getPath().contains("/login")||request.getURI().getPath().contains("/info")) {
            log.info("进入判断url");
            return chain.filter(exchange);
        }
        log.info("token信息:{}", token);

        if (StringUtils.isEmpty(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //设置响应头信息Content-Type类型
            response.getHeaders().add("Content-Type", "application/json");
            log.info("未携带token");
            return response.writeAndFlushWith(Flux.just(ByteBufFlux.just(response.bufferFactory().wrap(getWrapData()))));
        }

        String userId = JwtUntil.getUserId(token);
        String sourceToken = stringRedisTemplate.opsForValue().get(userId);
        log.info("redis中的token:{}", sourceToken);

        Map<String, Claim> claimMap = JwtUntil.parseJwt(token);
        if (claimMap == null) {
            //10. 解析jwt令牌出错, 说明令牌过期或者伪造等不合法情况出现
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //设置响应头信息Content-Type类型
            response.getHeaders().add("Content-Type", "application/json");
            log.info("token解析出错");
            return response.writeAndFlushWith(Flux.just(ByteBufFlux.just(response.bufferFactory().wrap(getWrapData()))));
        }

        //redis中无token信息
        if (sourceToken == null) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //设置响应头信息Content-Type类型
            response.getHeaders().add("Content-Type", "application/json");
            log.info("未携带token");
            return response.writeAndFlushWith(Flux.just(ByteBufFlux.just(response.bufferFactory().wrap(getWrapData()))));
        }

        //放行
        return chain.filter(exchange);
    }


    private byte[] getWrapData() {
        Map<String, Object> map = new HashMap<>();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data","无");
        map.put("code", 50008);
        map.put("message", "token为空或不合法");
        map.put("data", jsonObject);
        try {
            return new ObjectMapper().writeValueAsString(map).getBytes();
        } catch (JsonProcessingException e) {
            log.info("异常处理:{}", e.toString());
        }
        return "".getBytes();
    }

    @Override
    public int getOrder() {
        return 0;
    }

}
